<?php
/**
 * Created by PhpStorm.
 * User: CPR065
 * Date: 2016/9/30
 * Time: 16:53
 */

namespace Addon\Api\Controller;
class TicketController extends \Think\Controller{
    //tick eg url = https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2016-10-05&from_station=CDW&to_station=SHH
    public  $ticketUrl = 'https://kyfw.12306.cn/otn/lcxxcx/query';
    public $areaCodeUrl = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8968';
    public $codeTitle = [
        'ze_num' =>'二等座',
        'zy_num' =>'一等座',
        'swz_num' =>'商务座',
        'rw_num' =>'软卧',
        'rz_num' =>'软座',
        'qt_num' =>'其他',
        'yz_num' =>'硬座',
        'yw_num' =>'硬卧',
        'wz_num' =>'无座',
    ];

    /****
     * http://mycms.com/Home/Ticket/getTicket/addon/Api/from/%E6%AD%A6%E6%B1%89/to/%E9%94%A6%E5%B7%9E/date/2016-10-20
     */
    public function getTicket(){
        $date = I('get.date','','trim');
        $from = I('get.from','','trim');
        $to = I('get.to','','trim');
        if(empty($date) || empty($from) || empty($to)){
            $this->error('date,from,to 3个参数是必填选项!');
        }
        $fromCode = $this->getCodeByName($from);
        $toCode = $this->getCodeByName($to);
        $data=[
            'purpose_codes' =>'ADULT',
            'queryDate'=>$date,
            'from_station' => $fromCode,
            'to_station' => $toCode

        ];
        $rst = http($this->ticketUrl,$data);
        $data1 = json_decode($rst,true);
        $data = $data1['data']['datas'];
        $this->assign(
            [
                'data'=>$data,
                'codeTitle'=>$this->codeTitle
            ]
        );
        $info='';
        foreach($data as $k =>$v){
            $info .= '车次'.$v['station_train_code'].'发车时间：'.$v['start_time'].'到站时间：'.$v['arrive_time']
                .'耗时：'.$v['lishi'].'小时'.'硬座：'.$v['yz_num'].'硬卧:'.$v['yw_num'].'软卧'.$v['rw_num']."\n\r<br/><br/>";
        }
        echo $info;
        //$this->display();
    }

    /***@wha|武汉|WHN|wuhan|wh|65@
     * @param $name
     * @throws \Exception
     */
    public function getCodeByName($name){

        $data = http($this->areaCodeUrl,['time'=>time()]);
        preg_match('/@([a-z]+)\|'.$name.'\|([A-Z]+)\|([a-z]+)\|([a-z]+)\|([0-9]+)@/',$data,$match);
        if($match){
            return $match[2];
        }else{
            return false;
        }
    }
} 